package com.shujia.maven.jdbc;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;

    public class Demo2InsertIntoMysql {
        public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //创建连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://master:3306/db2?useSSl=false" , "root", "123456");
            //创建Statement
            Statement st = conn.createStatement();
            st.execute("create table if not exists student_like like student");
            //创建prepareStatement
            PreparedStatement preSet = conn.prepareStatement("insert into student_like values(?,?,?,?,?)");
            //读取数据
            BufferedReader br =new BufferedReader(new FileReader("data/students.txt")) ;
            String line;
            while((line=br.readLine())!=null){
                String[] splits=line.split(",");
                int id= Integer.parseInt(splits[0]);
                String name=splits[1];
                int age= Integer.parseInt(splits[2]);
                String gender=splits[3];
                String clazz=splits[4];
                //设置参数
                preSet.setInt(1,id);
                preSet.setString(2,name);
                preSet.setInt(3,age);
                preSet.setString(4,gender);
                preSet.setString(5,clazz);
                //执行插入
                preSet.executeUpdate();
            }
            //关闭连接
            st.close();
            preSet.close();
            conn.close();
        }
    }


